<?php

namespace App\Http\Middleware;

use App\admin;
use App\power;
use Closure;
use Illuminate\Support\Facades\Auth;

class AdminLogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $content = [
            'parameters' => $request->request->all(),
            'original' => $response->original
        ];

        if (!in_array($method = $request->getMethod(), ['GET', 'OPTIONS'])) {
            $data = [
                'admin_id' => $request->session()->get('session_id'),
                'name' => $request->session()->get('session_role_name'),
                'url' => $request->getPathInfo(),
                'content' => json_encode($content),
                'ip' => $request->getClientIp(),
                'controllers' => json_encode(request()->route()->getAction()),
                'useragent' => $request->server()['HTTP_USER_AGENT'],
                'created_at' => time()
            ];
            power::create($data);
        }

        return $response;
    }
}
